<template>
  <view class="address-info">
    <view class="cells padd30 page_bg_FAFAFA">
      <u-form labelPosition="left" :model="formData" ref="uForm" :borderBottom='false' :rules='rules'>
        <u-form-item prop="nameValue">
          <u-cell title="收货人" :border="false">
            <u-input border="none" slot="value" placeholder="请填写收货人姓名" v-model="formData.nameValue"></u-input>
          </u-cell>
        </u-form-item>
        <u-form-item prop="mobileValue">
          <u-cell title="手机号" :border="false">
            <u-input maxlength="11" type="number" border="none" slot="value" placeholder="请填写收货人手机号"
              v-model="formData.mobileValue"></u-input>
          </u-cell>
        </u-form-item>
        <u-form-item prop="addressArea">
          <u-cell title="所在地区" :border="false">
            <view slot="value" class="area">
              <picker mode='region' @change="chooseregion" style="width: 100%;">
                <u-input v-model="formData.addressArea" placeholder="请选择地址" disabled="true" border="none"
                  disabledColor="#FFFFFF"></u-input>
              </picker>
              <u-icon name="arrow-right" color="#999999" size="20"></u-icon>
            </view>
          </u-cell>
        </u-form-item>
        <u-form-item prop="addressValue">
          <u-cell title="详细地址" :border="false">
            <u-input slot="value" placeholder="请填写详细地址" border="none" v-model="formData.addressValue"></u-input>
          </u-cell>
    
        </u-form-item>
        <u-cell title="设置默认地址" :border="false">
          <u-switch slot="value" activeColor="#28A82E" inactiveColor="#D5D5D5" v-model="formData.switchValue"></u-switch>
        </u-cell>
        
      </u-form>
      
    </view>

    <t-button @handleBtnClick="saveAddress()" backGround="#FA312A" content="保存地址"></t-button>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        formData: {
          nameValue: '',
          mobileValue: '',
          addressValue: '',
          addressArea: '',
          switchValue: false,
          province: '', //省
          city: '', //城市
          region: '' //街区
        },
       
        userId: '',
        addressId: '',
        rules: {
          nameValue: [{
            type: 'string',
            required: true,
            message: '请填写收货人姓名',
            trigger: ['blur', 'change']
          }],
          mobileValue: [{
            type: 'string',
            required: true,
            message: '请填写收货人手机号',
            trigger: ['blur', 'change']
          },
          {
            type: 'string',
            required: true,
            len:11,
            message: '请填写11位手机号',
            trigger: ['blur', 'change']
          }
          ],
          addressArea: [{
            type: 'string',
            required: true,
            message: '请选择地址',
            trigger: ['blur', 'change']
          }],
          addressValue: [{
            type: 'string',
            required: true,
            message: '请填写详细地址',
            trigger: ['blur', 'change']
          }],
        },
      };
    },
    onReady() {
      //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
      this.$refs.uForm.setRules(this.rules)
    },
    async onLoad(query) {
      console.log('query', query);
      this.addressId = query.id
      await this.loadAddressDetails()
      this.userId = uni.getStorageSync('userInfo').id
    },
    // computed: {
    //   address() {
    //     if(this.formData.province && this.formData.city && this.formData.region) {
    //       return this.formData.province + '-' + this.formData.city + '-' + this.formData.region
    //     } else {
    //       return ''
    //     }
    //   }
    // },
    methods: {
      // 获取省市区
      chooseregion(event){
      		console.log(event.detail.value);
      		this.formData.province = event.detail.value[0]
      		this.formData.city = event.detail.value[1]
      		this.formData.region = event.detail.value[2]
      		if (this.formData.province && this.formData.city && this.formData.region) {
      		  this.formData.addressArea = this.formData.province + '-' + this.formData.city + '-' + this.formData.region
            console.log(this.formData.addressArea,'this.formData.addressArea');
            this.$refs.uForm.validateField('addressArea')
      		} else {
      		  return ''
      		}
      	},
        async loadAddressDetails() {
          try {
              const addressInfo = await uni.getStorage({ key: 'addressInfo' });
              if (addressInfo.data) {
                const info = addressInfo.data;
                this.formData.nameValue = info.name;
                this.formData.mobileValue = info.phoneNumber;
                this.formData.addressValue = info.detailAddress;
                this.formData.province = info.province;
                this.formData.city = info.city;
                this.formData.region = info.region;
                this.formData.switchValue = info.defaultStatus === 1;
              }
            } catch (error) {
              console.error('Error loading address details:', error);
            }
        },
        checkPhone() {
          const mobileRegex = /^1[3456789]\d{9}$/;
          if (this.formData.mobileValue === '' || !mobileRegex.test(this.formData.mobileValue)) {
            uni.showToast({
              title: '请输入正确手机号',
              icon: 'none',
            });
            return false;
          }
          return true;
        },
        async saveAddress() {
          // if (!this.checkPhone()) return
          this.$refs.uForm.validate()
          .then(async () => { 
          const res = await this.$http.put('/yaolexue-service-portal/receiveAddress/updateReceiveAddress', {
            name: this.formData.nameValue,
            phoneNumber: this.formData.mobileValue,
            detailAddress: this.formData.addressValue,
            userId: this.userId,
            province: this.formData.province,
            city: this.formData.city,
            region: this.formData.region,
            defaultStatus: this.formData.switchValue ? 1 : 0,
           id: this.addressId
          });
          if (res.code === 200) {
            uni.showToast({
              title: '修改成功',
              icon: 'none'
            })
            uni.redirectTo({
              url: '/subPages/selectAddress/selectAddress',
            });
          } else {
            console.error('修改地址失败', res.message);
          }
          console.log('saveAddress', res);
          })
        },
        // chooseAddress() {
        //   const res = uni.chooseLocation({
        //     success: (res) => {
        //       if (res.errMsg === 'chooseLocation:ok') {
        //         this.area = res.address;
        //       } else {
        //         uni.showToast({
        //           title: res.errMsg,
        //         });
        //       }
        //     },
        //   });
        // },
      },
  }
</script>

<style lang="scss">
  .address-info {
    .cells {
      .u-cell {
        margin-top: 20rpx;
        display: block;
        overflow: hidden;
        background-color: $color-toolbar;

        &:nth-child(5) {
          margin-top: 0;
        }
        
        ::v-deep .u-cell__title-text {
          // width: 100px !important;
        }

        .u-input {
          ::v-deep .u-input__content {
            width: 200px !important;
            .u-input__content__field-wrapper__field {
              text-align: right !important;
              
            }
           .uni-input-placeholder {
              
              letter-spacing: 1px;
            }
          }

        }

        .area {
          width: 400rpx;
          height: auto;
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }
</style>